define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'workorder/orders/index' + location.search,
                    add_url: 'workorder/orders/add',
                    edit_url: 'workorder/orders/edit',
                    del_url: 'workorder/orders/del',
                    multi_url: 'workorder/orders/multi',
                    import_url: 'workorder/orders/import',
                    records_url: 'workorder/orders/records',
                    table: 'workorder_orders',
                }
            });

            var table = $("#table");

            //默认字段
            var columns = [
                {checkbox: true},
                {field: 'id', title: __('Id'), operate: false},
                {
                    field: 'user.nickname',
                    title: __('User_id'),
                    addclass: 'selectpage',
                    extend: 'data-source="user/user/index" data-field="nickname"',
                    operate: '=',
                    formatter: Table.api.formatter.search
                },
                {
                    field: 'urgentrank.name',
                    title: __('Urgency'),
                    addclass: 'selectpage',
                    extend: 'data-source="workorder/urgentrank/index" data-field="name"',
                    operate: '=',
                    formatter: Table.api.formatter.search
                },
                {
                    field: 'category.name',
                    title: __('Category_id'),
                    addclass: 'selectpage',
                    extend: 'data-source="workorder/category/index" data-field="name"',
                    operate: '=',
                    formatter: Table.api.formatter.search
                },
                {
                    field: 'engineers.title',
                    title: __('Engineer_id'),
                    addclass: 'selectpage',
                    extend: 'data-source="workorder/engineers/index" data-field="title"',
                    operate: '=',
                    formatter: Controller.api.formatter.search
                }
            ];
            //动态追加字段
            $.each(Config.fields, function (i, j) {
                var data = {field: j.field, title: j.title, operate: 'like'};
                //如果是图片,加上formatter
                if (j.type == 'image') {
                    data.formatter = Table.api.formatter.image;
                } else if (j.type == 'images') {
                    data.formatter = Table.api.formatter.images;
                } else if (j.type == 'radio' || j.type == 'checkbox' || j.type == 'select' || j.type == 'selects') {
                    data.formatter = Controller.api.formatter.values;
                    data.extend = j.values;

                    let values_obj = {};
                    for (var item in j.values) {
                        values_obj[item] = j.values[item];
                    }
                    data.searchList = values_obj
                } else if (j.field == 'title') {
                    data.formatter = Controller.api.formatter.valueSubstring;
                }
                columns.push(data);
            });
            columns.push({
                field: 'status',
                title: __('Status'),
                searchList: {
                    "0": __('Status 0'),
                    "1": __('Status 1'),
                    "2": __('Status 2'),
                    "3": __('Status 3'),
                    "4": __('Status 4'),
                    "5": __('Status 5')
                },
                formatter: Table.api.formatter.status
            });
            columns.push({
                field: 'updatetime',
                sortable: true,
                title: __('Updatetime'),
                operate: 'RANGE',
                addclass: 'datetimerange',
                formatter: Table.api.formatter.datetime
            });
            columns.push({
                field: 'createtime',
                sortable: true,
                title: __('Createtime'),
                operate: 'RANGE',
                addclass: 'datetimerange',
                formatter: Table.api.formatter.datetime
            });
            //追加操作字段
            columns.push({
                field: 'operate',
                title: __('Operate'),
                table: table,
                events: Table.api.events.operate,
                formatter: Table.api.formatter.operate,
                buttons: [
                    {
                        name: 'records',
                        title: '查看沟通记录',
                        classname: 'btn btn-xs btn-info btn-dialog',
                        icon: 'fa fa-file-text-o',
                        url: $.fn.bootstrapTable.defaults.extend.records_url,
                    }
                ]
            });

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                columns: columns
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        records: function () {
            $.fn.popover.Constructor.DEFAULTS.sanitize = false;
            $("[rel=engineer_popo]").popover({
                trigger: 'manual',
                title: this.title,
                html: true,
                content: function () {
                    let engineer_id = $(this).data('engineer_id');
                    return $('.engineer_info_' + engineer_id).html();
                },
                animation: true
            }).on("mouseenter", function () {
                var _this = this;
                $(this).popover("show");
                $(this).siblings(".popover").on("mouseleave", function () {
                    $(_this).popover('hide');
                });
            }).on("mouseleave", function () {
                var _this = this;
                setTimeout(function () {
                    if (!$(".popover:hover").length) {
                        $(_this).popover("hide")
                    }
                }, 100);
            });

            $("[rel=userInfo_popo]").popover({
                trigger: 'manual',
                title: this.title,
                html: true,
                content: function () {
                    return $('.user_info').html();
                },
                animation: true
            }).on("mouseenter", function () {
                var _this = this;
                $(this).popover("show");
                $(this).siblings(".popover").on("mouseleave", function () {
                    $(_this).popover('hide');
                });
            }).on("mouseleave", function () {
                var _this = this;
                setTimeout(function () {
                    if (!$(".popover:hover").length) {
                        $(_this).popover("hide")
                    }
                }, 100);
            });

            $(document).on('click', '.item_meta_text img', function (e) {
                var img_obj = $(e.target)[0];
                if (img_obj) {
                    var scrollTop = $(window).scrollTop();
                    layer.photos({
                        photos: {
                            "title": "图片预览",
                            "id": "recordimg",
                            data: [
                                {
                                    "src": img_obj.src
                                }
                            ]
                        },
                        end: function () {
                            $(window).scrollTop(scrollTop)
                        },
                        anim: 5
                    });
                }
            })
        },
        recyclebin: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    'dragsort_url': ''
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: 'workorder/orders/recyclebin' + location.search,
                pk: 'id',
                sortName: 'id',
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'title', title: __('Title'), align: 'left', formatter: Controller.api.formatter.valueSubstring},
                        {
                            field: 'deletetime',
                            title: __('Deletetime'),
                            operate: 'RANGE',
                            addclass: 'datetimerange',
                            formatter: Table.api.formatter.datetime
                        },
                        {
                            field: 'operate',
                            width: '130px',
                            title: __('Operate'),
                            table: table,
                            events: Table.api.events.operate,
                            buttons: [
                                {
                                    name: 'Restore',
                                    text: __('Restore'),
                                    classname: 'btn btn-xs btn-info btn-ajax btn-restoreit',
                                    icon: 'fa fa-rotate-left',
                                    url: 'workorder/orders/restore',
                                    refresh: true
                                },
                                {
                                    name: 'Destroy',
                                    text: __('Destroy'),
                                    classname: 'btn btn-xs btn-danger btn-ajax btn-destroyit',
                                    icon: 'fa fa-times',
                                    url: 'workorder/orders/destroy',
                                    refresh: true
                                }
                            ],
                            formatter: Table.api.formatter.operate
                        }
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();
        },
        edit: function () {
            Controller.api.bindevent();
        },
        api: {
            bindevent: function () {
                Form.api.bindevent($("form[role=form]"));
            },
            formatter: {
                values: function (value, row, index) {
                    var extend = this.extend;
                    if (!value) {
                        return '';
                    }
                    var valueArr = value.toString().split(/,/);
                    var result = [];
                    $.each(valueArr, function (i, j) {
                        result.push(typeof extend[j] !== 'undefined' ? extend[j] : j);
                    });
                    return result.join(',');
                },
                search: function (value, row, index) {
                    if (!value) {
                        return '无';
                    } else {
                        var that = $.extend({}, this);
                        var table = $(that.table).clone(true);
                        that.table = table;
                        return Table.api.formatter.search.call(that, value, row, index);
                    }
                },
                valueSubstring: function (value) {
                    let valueLength = value.replace(/[\u0391-\uFFE5]/g, "aa").length;
                    return valueLength > 30 ? value.substring(0, 30) + '...' : value;
                }
            }
        }
    };
    return Controller;
});